package keter.framework.web.handler;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import keter.framework.exception.KeterFileException;
import keter.framework.exception.runtime.KeterValidateException;
import keter.framework.web.util.RequestUtil;
import keter.framework.web.util.ResponseUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.google.common.collect.Maps;

/**
 * <p>
 * Class : keter.web.handler.KeterExceptionHandler
 * <p>
 * Descdription: 运行时异常全部被捕获
 * 
 * @author gulixing@msn.com
 * @version 1.0.0
 */
public class KeterExceptionResolver extends SimpleMappingExceptionResolver {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(KeterExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
 		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		String s = (String) request.getParameter("showerror");
		if(RequestUtil.isAjax(request)) {// JSON格式返回
			ResponseUtil.print("error:'true',message:'"+ex.getMessage()+"'", response);
            return new ModelAndView();
		}
		else if (ex instanceof AccessDeniedException ) {//非法访问
//			 ex.printStackTrace();
		     logger.error("用户 [{}]尝试非法访问资源[{}]!",getUserFromSession(request.getSession()).getUsername(),request.getServletPath());
		     return new ModelAndView("keter/common/403");
		}
		else if (ex instanceof KeterFileException ) {//可感知的文件上传相关异常
			Map<String, String> map = Maps.newHashMap();
			map.put("message",ex.getMessage());
			map.put("detail", ((KeterFileException) ex).getDetail());//文件无法访问或已被删除，请联系管理员！
			return new ModelAndView("keter/common/showerror", map);
		}
		else if (ex instanceof KeterValidateException ) {//后台数据校验异常
		    logger.error(ex.getMessage());
		    return new ModelAndView("keter/common/error");
		}
		else if (s!=null && s.equals("true")) {// 页面需要自定义异常
		    return customEx(ex);
		}
	    logger.error("系统异常：", ex);
		return new ModelAndView("keter/common/error");
	}
	
	private UserDetails getUserFromSession(HttpSession session){
	     SecurityContextImpl ctx = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
	     return (UserDetails)ctx.getAuthentication().getPrincipal();
	}

	private ModelAndView customEx(Exception ex) {
		Map<String, String> map = Maps.newHashMap();
		String message = ex.getMessage();
		String cause = ex.getCause() != null ? ex.getCause().toString() : "";
		map.put("message", message);
		map.put("cause", cause);
		return new ModelAndView("/framework/errors/showerror", map);
	}

	public static void main(String[] args) {
		ModelAndView mav = new ModelAndView();
		System.out.println(mav.isEmpty());
	}
}
